﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Xml.Serialization;

namespace Microsoft.Mtool.FSM
{
    [Serializable]
    public class Variable
    {
        private string name;
        private bool isVar;
        private List<string> values = new List<string>();

        [XmlAttribute]
        public string Name
        {
            get { return name; }
            set 
            { 
                name = value;
                if (name != null)
                    isVar = IsVariable(name);
            }
        }

        private bool IsVariable(string text)
        {
            return (text[0] == '_') || (text[0] >= 'a' && text[0] <= 'z') || (text[0] >= 'A' && text[0] <= 'Z');
        }

        [XmlIgnore]
        public bool IsVar
        {
            get { return isVar; }
            /* NO SETTER: always set by 'Name' */
        }

        [XmlIgnore]
        public List<string> Values
        {
            get { return values; }
            /* NO SETTER: because always use the default instance and set by 'MergedValues' */
        }

        [XmlAttribute]
        public string MergedValues
        {
            get
            {
                if (values.Count == 0)
                    return "";
                else if (values.Count == 1)
                    return values[0];
                StringBuilder sb = new StringBuilder();
                sb.Append(values[0]);
                for (int i = 1; i < values.Count; ++i)
                    sb.Append(",").Append(values[i]);
                return sb.ToString();
            }
            set
            {
                values.Clear();

                if (value == null)
                    return;
                string[] segs = value.Split(',');
                foreach (string seg in segs)
                {
                    string trimSeg = seg.Trim();
                    if (!string.IsNullOrEmpty(trimSeg))
                        values.Add(trimSeg);
                }
            }
        }
    }
}